<!--//考试过程页面-->
<template>
	<view class="home"  @touchend='doubleClick'>
		<view>
			<uni-nav-bar class="nav" color="white" left-icon="back" left-text="返回" title="在线考试"
				backgroundColor="#3498DB" @clickLeft="backToTestList()">
				<!-- 倒计时 -->
				<view class="countdown">
					<!-- @timeup指倒计时时间到的触发事件 -->
					<uni-countdown backgroundColor="#3498DB" color="white" splitorColor="white" :showDay="false"
						:hour="testDDL.hour" :minute="testDDL.minute" :second="testDDL.second"
						@timeup="goToTestSuccess()">
					</uni-countdown>
				</view>
			</uni-nav-bar>
		</view>
		<!-- 进度条 -->
		<view class="progress">
			<!-- 进度条组件 -->
			<!-- percent指完成进度  show-info指是否显示百分比 stroke-color指进度条颜色 -->
			<cmd-progress :percent="number/$store.state.questions.length*100" :show-info="false" stroke-color="#6ed90a"></cmd-progress>
		</view>
		<!-- 问题部分 -->
		<view class="questions">
			<!-- v-bind:current=nowPage属性动态绑定页面跳转 -->
			<swiper class="swiper" :current="this.now" :indicator-dots="false" duration="0" @change="getIndex" v-bind:current=nowPage>
				<swiper-item v-for="(item,index) in this.$store.state.questions" >
					<!-- 题目序号与类型 -->
					<view class="numbers">
						{{(index+1)+"."}}
						<view class="types">
							{{item.type}}
						</view>
					</view>
					<!-- 题目内容 -->
					<view class="text">
						<!-- <rich-text :nodes="item.text"></rich-text> -->
						<p v-html="item.text"></p>
					</view>
					<!-- 题目分值 -->
					<view class="scores">
						分值：{{item.score}}分
					</view>
					<!-- 选择题选项样式 -->
					<view class="radioss" v-show="isChoice">
						<radio-group class="radios" @change="radioChange">
							<label v-for="(it,ind) in item.options" :key="it.value" class="rad">
								<view>
									<radio class="radio" :value="it.value" :checked="ind === current" color="#007AFF" />
								</view>
								<view class="text"><!-- {{alphabet[ind]}}. --><p v-html="it.text"></p></view>
							</label>
						</radio-group>
					</view>
        <!--  判断题样式-->
          <view class="radioss" v-show="isJudege">
            <radio-group class="radios" @change="judegeChange">
               <label class="rad">
                 <view>
                   <radio class="radio" :value="judgeChoice.right" color="#007AFF" />
                 </view>
                 <view class="text">{{judgeChoice.right}}</view>
               </label>
             <label class="rad">
               <view>
                 <radio class="radio" :value="judgeChoice.error" color="#007AFF" />
               </view>
               <view class="text">{{judgeChoice.error}}</view>
             </label>
            </radio-group>
          </view>
					<!-- 填空题样式 -->
					<view class="radioss" v-show="isGap">
						<input class="Completion" v-model="item.answer[n]" v-for="(i,n) in item.answer" type="text"/>
            <!--						<textarea class="in" @blur="bindTextAreaBlur" placeholder="请输入答案"></textarea>-->
					</view>
					<!-- 简答题样式 -->
					<view class="radioss" v-show="isComprehensive">
						<!-- <button class="shoot" hover-class="active" @click="upImages(item.id,index)">点击拍照上传答案</button> -->
						<!-- <image v-if=isPic class="img" :src=list[index-countNum] @click="previewImg(item)"></image> -->
						<imgUpload :backNum="number-1" ></imgUpload>
						<!-- <image class="img" src="this,imgArr"></image> -->
					</view>
				</swiper-item> 
			</swiper>
		</view>
		<!-- 答题状态栏 -->
		<view class="states" v-if="this.bool">
			<circulate ref="changeDetail" @pageChange="pageChange">
			</circulate>
		</view>
		<button class="submit" hover-class="active" @click="open">交卷</button>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog class="popMessage" type="info" mode="base" 
			:content="this.context" :beforeClose="true"
				:duration="0" @close="close" @confirm="confirm">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	// 模拟接口
	import {
		//getTestDDL,
		getQuestions,
		putupPaper,
		upload
	} from '../../api/file.js'
	// 考试状态组件
	import circulate from "../../components/testDetail/testing-circulate.vue"
	// 进度条组件
	import cmdProgress from "@/components/cmd-progress/cmd-progress.vue"
	//上传图片组件
	import imgUpload from "@/components/img-upload/file-picker.vue"
	export default {
		components: {
			cmdProgress,
			circulate,
			imgUpload
		},
		data() {
			return {
				isPic:false,
				countNum:0,
				list:[],
        judgeChoice:{
          right:'√',
          error:'X'
        },
        s:3,
        nowPage:0,
				//组件当前所在题号
				now:0,
				//提交时弹出信息
				context:"",
				testDDL: { // 倒计时时间
					hour: 1,
					minute: 40,
					second: 0,
				},
				token:uni.getStorageSync('token'),
				userId:uni.getStorageSync("studentNum"),
				paperId:uni.getStorageSync("paperId"),
				testId:uni.getStorageSync("testCode"),
				url: "/pages/testList/testList",
				// 题目类型
				isChoice: true,
				isGap: false,
				isComprehensive: false,
        isJudege:false,
				//图片
				imgArr:"",
				percent:0,
				loading:false,
				disabled:false,
				exampleImg:"../../static/images/pic.jpg",
				// 进度条
				number: 1,
				//totalNum: 11,
				// 选择题选项名
				alphabet: ['A', 'B', 'C', 'D', 'E', 'F', 'G',
					'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
					'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
				],
				// 选择题当前选择选项
				current: -1,
				// 答题状态栏
				bool: false,
				startData: {
					clientX: 0,
					clientY: 0
				},
				questionPaper: {
					sumScore: 0
				},
				// 交卷状态判断
				// putup: false,
			}
		},
		onLoad() {
			//this.now=option.id;
			const that = this.$event
			this.getIndex(that);
		},
		created(){
			//传递考试剩余时间用于倒计时
			this.countNum=uni.getStorageSync('count');
			this.testDDL.minute=uni.getStorageSync('minute');
			this.testDDL.hour=uni.getStorageSync('hour');
			this.testDDL.second=uni.getStorageSync('second');
			console.log("倒计时开始的时间hours,minutes,seconds",this.testDDL.hour,this.testDDL.minute,this.testDDL.second)
		},
		methods: {
      pageChange(page){       //子组件circulate向父组件传数据
        this.nowPage = page;
        console.log("页面调整---"+this.nowPage)
      },
			// 界面跳转
			backToTestList() {
				this.$router.push(this.url);
			},
			goToTestSuccess() {
				putupPaper({paperId:this.paperId,token:this.token,userId:this.userId,questionAnswer:this.$store.state.questions}).then(res => {
				  console.log("提交:",res);
				  if (res.data.code===200)
				    this.putup = true;
				  if (this.putup===true){
				    this.$router.push("/pages/testSuccess/testSuccess")
				  }
				  else{
				    alert("提交失败,请重新提交~~");
				  }
				})
			},
			//选择图片上传
			// upImages(questionId,index) {
			// 	let userId="234hkwef";
			// 	uni.chooseImage({
			// 		count: 2, //默认9
			// 		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			// 		sourceType: ['camera','album'], //使用相机
			// 		success: (res)=> {  //通过箭头函数处理this指向问题
			// 			console.log("图片的res",res);
			// 			console.log("图片的res.tempFilePaths",JSON.stringify(res.tempFilePaths));//拿到选择的图片，是一个数组
   //                      console.log("图片的path",res.tempFiles[0].path)
			// 			//console.log("图片的path",data.data);
			// 			//this.imgArr=res.tempFilePaths;
			// 			const tempFiles = res.tempFiles;
			// 			upload({file: res.tempFiles[0].path,
			// 			userId,questionId}).then(data=>{     //通过then方法处理返回的promise对象
			// 				this.isPic=false
			// 				 console.log("图片的data",data);
			// 				 this.list[index-this.countNum]=data.data;
			// 				 this.$store.commit("GetAnswer",{number:this.number-1,text:this.list[index-this.countNum]});
			// 				 this.isPic=true
			// 				 ///this.imgArr=data.data;
			// 				 //console.log(list);
			// 			});
			// 			}
			// 	});
			// 	//this.manswer[this.number-1].answerText=this.imgArr;
			// },
			previewImg(current){
				uni.previewImage({
					current,
					urls:this.imgArr
				})
			},
			// 获取swiper索引值
			// 判断题目类型
			getIndex(e) {
				this.number = e.detail.current + 1;
				if (this.$store.state.questions[e.detail.current].type == "选择题") {
					this.isChoice = true;
					this.isGap = false;
					this.isComprehensive = false;
          this.isJudege =false;
				} else if(this.$store.state.questions[e.detail.current].type=="判断题"){
          this.isChoice =false;
          this.isGap = false;
          this.isComprehensive = false;
          this.isJudege =true;
        }
        else if (this.$store.state.questions[e.detail.current].type == "填空题") {
					this.isChoice = false;
					this.isGap = true;
					this.isComprehensive = false;
          this.isJudege =false;
				} else if (this.$store.state.questions[e.detail.current].type == "简答题") {
					this.isChoice = false;
					this.isGap = false;
					this.isComprehensive = true;
          this.isJudege =false;
				}
			},
			// 选择题选项
			radioChange: function(evt) {
				console.log("evt:",evt);
				this.$store.commit("GetAnswer",{number:this.number-1,text:evt.detail.value});  //将选择题选项数据更新到vuex仓库中相应的位置
			},
      // 判断题选项
      judegeChange(evt){
        console.log("判断题的evt",evt)
        this.$store.commit("GetAnswer",{number:this.number-1,text:evt.detail.value})  //将判断题选项数据更新到vuex仓库中相应的位置
      },

      // 双击事件
      doubleClick(e){
        const _now = new Date().getTime()
        if (_now - this.touchStartTime <= 300) {
          if(this.bool == false){
            this.bool=true           //将子组件显示出来
          }
          else
            this.bool=false
          console.log('这是双击事件')
          console.log(this.bool);
        } else {
          this.touchStartTime = _now
        }
      },
			// 综合题拍照
			takePhoto() {
				const ctx = uni.createCameraContext();
				ctx.takePhoto({
					quality: 'high',
					success: (res) => {
						this.src = res.tempImagePath
					}
				});
			},
			// 答题状态栏
			pop() {
				return this.bool;
			},
			getChild(e) {
				this.questionPaper.sumScore = e;
			},
			// // touch事件监听，start获取手指开始位置，end获取手指结束位置
			// start(e) {
			// 	this.startData.clientX = e.changedTouches[0].clientX;
			// 	this.startData.clientY = e.changedTouches[0].clientY;
			// },
			// end(e) {
			// 	const subX = e.changedTouches[0].clientX - this.startData.clientX;
			// 	const subY = e.changedTouches[0].clientY - this.startData.clientY;
			// 	// 判断滑动，bool控制答题状态栏是否出现
			// 	if (subY < -100) {
			// 		this.bool = true;
			// 	} else if (subY > 100 || subY == 0) {
			// 		this.bool = false;
			// 	}
			// },

			// 是否交卷提示
			open() {
				console.log("选择提交时的打印questions:",this.$store.state.questions);
				this.context="确认现在提交吗？";
        for (let i =0; i<this.$store.state.questions.length; i++) {
          if (this.$store.state.questions[i].answer.includes("")===true) {
            console.log("this.$store.state.questions[i]",this.$store.state.questions[i]);
            this.context="你还有题目没写完,确认现在提交吗？";
            break;
          }
        }
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},
			// 取消
			close() {
				this.$refs.popup.close()
			},
			// 确定,提交考试信息
			confirm() {
        console.log(this.paperId)
        putupPaper({paperId:this.paperId,token:this.token,userId:this.userId,testId:this.testId,
		questionAnswer:this.$store.state.questions}).then(res => {
          console.log("提交:",res);
          if (res.data.code===200)
            this.putup = true;
          if (this.putup===true){
            this.$router.push("/pages/testSuccess/testSuccess")
          }
          else{
            alert("提交失败,请重新提交~~");
          }
          this.$refs.popup.close();
        })
			},
		}
	}
</script>

<style lang="scss" scoped>
	// 全局
	.home {
		height: 1200rpx;
		color: #3d3d3d;
	}

	/* 倒计时 */
	.countdown {
		display: flex;
		flex-direction: row;
		position: absolute;
		right: 10rpx;
	}

	/* 问题部分 */
	.questions {
		top: -15rpx;
		margin: 15rpx;
		position: relative;
	}

	/* swiper区域 */
	.swiper {
		height: 1100rpx;
	}

	// 题目序号
	.numbers {
		display: flex;
		flex-direction: row;
	}

	// 题目类型
	.types {
		font-size: 30rpx;
		color: #5FADFF;
		border-radius: 10rpx;
		border-style: solid;
		border-width: 3rpx;
		border-color: #5FADFF;
	}

	// 题目分数
	.scores {
		color: #686868;
		background-color: #e1e1e1;
		width: 170rpx;
		margin: 10rpx;
		position: absolute;
		right: 0;
	}

	/* 选择题样式 */
	.radioss {
		margin-top: 60rpx;
		display: flex;
		flex-direction: column;
		width: 100%;
	}

	.radios {
		display: flex;
		flex-direction: column;
		margin: 15rpx;
	}

	// 实现自动换行
	.text {
		word-break: break-all;
		word-wrap: break-word
	}

	// radio按钮大小
	.radio {
		transform: scale(0.8);
	}

	.rad {
		margin-bottom: 25rpx;
		display: flex;
		flex-direction: row;
		width: 98%;
	}

	/* 填空题样式 */
	.in {
		width: 90%;
		border-radius: 10rpx;
		border-style: solid;
		border-width: 3rpx;
		border-color: #595959;
		margin-left: 30rpx;
		margin-right: 30rpx;
	}

	/* 综合题样式 */
	.shoot {
		width: 80%;
		background-color: #03abff;
		color: white;
	}
	/*上传图片*/
	.img{
		width: 80%;
		// justify-content: center;
		align-content: center;
		padding-top: 20rpx;
		padding-left: 70rpx;

	}
	/* 答题状态 */
	.states {
		width: 100%;
		background-color: #e1f6ff;
		border-radius: 15rpx;
		position: absolute;
		bottom: 95rpx;
	}

	.state {
		margin: 10rpx;
	}

	/* 提交按钮 */
	.submit {
		position: absolute;
		bottom: 0;
		width: 100%;
		border-radius: 0;
		background-color: #3498DB;
		color: white;
	}

	/* 按钮点击效果 */
	.active {
		background-color: #0287ca;
	}

  .Completion{
    border-bottom: solid 1px;
    width: 80%;
    margin-top:20px;
  }
</style>
